package org.replay.utils;/*
 * Copyright © 2020 lizicong,All rights reserved.
 *
 * Licensed under the GPL License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 自主签收式消息发送器
 * @author lizicong
 */

@Component
public class RabbitACKSender implements RabbitTemplate.ConfirmCallback {

    /**
     * RabbitMQ客户端
     */
    public final RabbitTemplate rabbitTemplate;


    /**
     * 为RabbitTemplate实例开启自主签收模式
     *
     * @param rabbitTemplate
     */
    @Autowired
    private RabbitACKSender(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this);
    }


    /**
     * 消息发送状态判断模块
     *
     * @param correlationData 自定义的ack序列码
     * @param isOK            签收状态
     * @param cause           错误原因(如果消息发送无异常.则为null)
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean isOK, String cause) {
        //消息发送成功
        if (isOK) {
            System.out.println("isOK:" + isOK + " confirm:" + correlationData.getId());
        }
        //消息发送失败，打日志，有需要的话可以供其它系统根据日志来进行补偿
        else {
            System.out.println("isOK:" + isOK + " confirm:" + correlationData.getId() + ",cause=" + cause);
        }
    }


    //嵌入式ack应答器(重复代码多，不采用)
    //    @Bean
    //    @Scope("prototype")
    //    public static RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
    //        RabbitTemplate template = new RabbitTemplate(connectionFactory);
    //        template.setMandatory(true);
    //        template.setMessageConverter(new SerializerMessageConverter());
    //        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
    //            @Override
    //            public void confirm(CorrelationData correlationData, boolean isOK, String cause) {
    //                System.out.println("confirm: " + correlationData.getId() + ",isOK:" + isOK + ",cause=" + cause);
    //            }
    //        });
    //        return template;
    //    }

}
